/**
 * 
 */
package xj.toolkit.ebus.unit;

import java.util.Iterator;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import xj.toolkit.ebus.Constants;
import xj.toolkit.ebus.EventBus;
import xj.toolkit.ebus.actors.AbstractEventActor;
import xj.toolkit.util.SimpleRegistry;

/**
 * @author hp
 *
 */
public class UnitGroupBooter extends AbstractEventActor {

	private static final Logger logger = LoggerFactory
			.getLogger(UnitGroupBooter.class);

	private Runnable canceler;
	private UnitGroupManager manager;
	private ApplicationContext rootAppCtx = null;

	/**
	 * @param cfgXmlpath
	 * @see xj.toolkit.ebus.unit.UnitGroupManager#setCfgXmlpath(java.lang.String)
	 */
	public void setCfgXmlPath(String cfgXmlPath) {
		manager.setCfgXmlLocations(new String[] { cfgXmlPath });
	}

	public void setCfgXmlLocations(String[] locations) {
		manager.setCfgXmlLocations(locations);
	}

	/**
	 * @return the rootAppCtx
	 */
	public ApplicationContext getRootAppCtx() {
		return rootAppCtx;
	}

	/**
	 * @param rootAppCtx
	 *            the rootAppCtx to set
	 */
	public void setRootAppCtx(ApplicationContext rootAppCtx) {
		this.rootAppCtx = rootAppCtx;
	}

	public UnitGroupBooter(final EventBus ebus, final SimpleRegistry registry) {
		super(ebus, "ebus booter");
		manager = new UnitGroupManager(ebus, registry);
	}

	public UnitGroupBooter(EventBus ebus, String name,
			final SimpleRegistry registry) {
		super(ebus, "ebus booter " + name);
		manager = new UnitGroupManager(ebus, registry);
	}

	@SuppressWarnings("unused")
	private void onEventGroup(String groupName, Iterator<UnitSource> itr) {
		if (logger.isDebugEnabled()) {
			logger.debug(groupName + " changed.");
		}
		manager.doUnitsChanged(groupName, itr, rootAppCtx);
	}

	public void start() {
		canceler = registerObserver(Constants.EVENT_UNITS_CHANGED, this, "onEventGroup");
	}

	@Override
	public void destroy() {
		try {
			canceler.run();
			manager.destroy();
		} catch (Exception e) {
			logger.error("destroy:", e);
		}

		super.destroy();
	}

	/**
	 * @return
	 * @throws Exception
	 * @throws
	 * @see stc.skymobi.ebus.unit.UnitGroupManager#getAllUnitGroup()
	 */
	public Map<String, String> getAllUnitGroup() throws Exception {
		return manager.getAllUnitGroup();
	}

}
